// pages/home/home_page.dart
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:hive/hive.dart';
import 'package:intl/intl.dart';
import 'package:zywz/bloc/auth/auth_bloc.dart';

import '../../api/api_client.dart';
import '../../bloc/auth/auth_event.dart';
import '../../bloc/auth/auth_state.dart';
import '../../bloc/home/home_bloc.dart';
import '../../bloc/home/home_event.dart';
import '../../bloc/home/home_state.dart';
import '../../bloc/home/homeother/home_btm_more_bloc.dart';
import '../../dialog/EnterpriseBindingDialog.dart';
import '../../models/financial_summary.dart';
import '../../models/user.dart';
import '../../models/user_company.dart';
import '../../widgets/EmptyPlaceholder.dart';
import '../../widgets/financial_card.dart';
import '../../config/app_colors.dart';
import '../../generated/assets.dart'; // 导入资源文件

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;


  var selectedYear = DateTime.now().year;
  var jidu = '第一季度';
  var jiduNum = 0;

  @override
  void initState() {
    super.initState();
    // context.read<HomeBloc>().add(LoadHomeinit());
    jidu = getCurrentQuarterString();
    jiduNum = getCurrentQuarter()-1;
    //context.read<HomeBtmMoreBloc>().add(HomeBtmYearJiDuEvent(jiduNum -1),);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<HomeBloc>().add(LoadHomeinit());
      var companyId = context.read<AuthBloc>().userBox.get('currentUser')?.appCompanyDto?.id ?? '';
      if(companyId.isNotEmpty) {
        context.read<HomeBtmMoreBloc>().add(HomeBtmYearJiDuEvent(jiduNum));
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('章鱼问账'),
        backgroundColor: const Color(0xFFE3F2FD),
        elevation: 0,
        centerTitle: true,
      ),
      body: BlocListener<AuthBloc, AuthState>(
        listener: (context, state) {
          if (state is AuthAuthenticated) {
            // 刷新数据
            print("LoadHomeData    HomeHaveCompany    初始化的时候，加载数据");
            // context.read<HomeBloc>().add(LoadHomeData(selectedYear));
            context.read<HomeBtmMoreBloc>().add(HomeBtmYearEvent(selectedYear));
            context.read<HomeBtmMoreBloc>().add(HomeBtmYearJiDuEvent(jiduNum));
          }
        },
        child: BlocListener<HomeBloc, HomeState>(
          listener: (context, state) async {
            if (state is HomeHaveCompany) {
              //初始化的时候，加载数据
              print("LoadHomeData    HomeHaveCompany    初始化的时候，加载数据");
              context.read<HomeBloc>().add(LoadHomeData(selectedYear));
            } else if (state is HomeNoCompany) {
              final result = await EnterpriseBindingDialog.show(context);
              if (result != null) {
                context.read<HomeBloc>().add(
                  AddCompany(LinkedHashMap<String, dynamic>.from(result)),
                );
                // 处理返回的数据
                print('企业信息: $result');
              }
            } else if (state is HomeAddSuccess) {
              // 添加企业信息正常的时候，需要重新加载数据
              print("LoadHomeData    HomeAddSuccess    添加企业信息正常的时候，需要重新加载数据");
              context.read<HomeBloc>().add(LoadHomeData(selectedYear));



              // context.read<AuthBloc>().add(AppStarted());
            } else if (state is HomeLoadFailure) {
              // 显示错误信息
              EasyLoading.showToast(state.error);
            }
          },
          child: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFE3F2FD), Color(0xCCE3F2FD)],
                stops: [0.0, 0.4],
              ),
            ),
            child: BlocBuilder<HomeBloc, HomeState>(
              builder: (context, state) {
                // 加载中
                if (state is HomeLoading) {
                  return const Center(
                    child: SpinKitFadingCircle(
                      color: Color(0xFF41C7DD),
                      size: 50.0,
                    ),
                  );
                }
                // 加载成功 有企业
                if (state is HomeLoadSuccess) {

                  print("LoadHomeData    HomeLoadSuccess    ${state.summary}");

                  return RefreshIndicator(
                    onRefresh: () async {
                      print("LoadHomeData    HomeHaveCompany    下拉刷新的时候，加载数据");
                      context.read<HomeBloc>().add(LoadHomeData(selectedYear));
                    },
                    child: _buildHomeContent(context, state.summary),
                  );
                }
                // 没有绑定企业
                if (state is HomeNoCompany) {
                  return RefreshIndicator(
                    onRefresh: () async {
                      print("LoadHomeData    HomeNoCompany    下拉刷新的时候，加载数据");
                      context.read<HomeBloc>().add(LoadHomeData(selectedYear));
                    },
                    child: Center(
                      child: EmptyPlaceholder(message: state.message),
                    ),
                  );
                }
                // 加载失败
                if (state is HomeLoadFailure) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('加载失败: ${state.error}'),
                        const SizedBox(height: 20),
                        ElevatedButton(
                          onPressed: () {
                            print(
                              "LoadHomeData    HomeLoadFailure    初始化的时候，加载数据",
                            );
                            context.read<HomeBloc>().add(LoadHomeData(selectedYear));
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF41C7DD),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(30),
                            ),
                          ),
                          child: const Text('重试'),
                        ),
                      ],
                    ),
                  );
                }
                return const Center(child: Text('请先加载数据'));
              },
            ),
          ),
        ),
      ),
    );
  }


  // 构建主页内容
  // 构建主页内容
  // 构建主页内容
  Widget _buildHomeContent(BuildContext context, Map<String, dynamic> summary) {
    var user = Hive.box<User>('user_box').get('currentUser');
    print(
      "_buildHomeContent : ${user?.appCompanyDto?.name}----------------- summary :$summary -------",
    );

    return ListView(
      padding: const EdgeInsets.all(16.0),
      children: [

        BlocSelector<AuthBloc, AuthState, AppCompanyDto?>(
          selector: (state) {
            if (state is AuthAuthenticated) {
              return state.user?.appCompanyDto;
            }
            return null;
          },
          builder: (BuildContext context, AppCompanyDto? state) {
            print(" 切换公司名称 _buildHomeContent : ${state?.name}");
            return  _buildCompanyHeader(state?.name ?? '未绑定企业');
          },
        ),


        // BlocSelector<HomeBloc, HomeState, Map<String, dynamic>?>(
        //   selector: (state) {
        //     if (state is HomeLoadSuccess) {
        //       return state.summary;
        //     }
        //     return null;
        //   },
        //   builder: (BuildContext context, Map<String, dynamic>? state) {
        //     print(" 切换公司名称 _buildHomeContent : ${state}");
        //     return   _buildProfitCard(state??{});
        //   },
        // ),

        _buildProfitCard(summary),
        // const SizedBox(height: 16),

        const SizedBox(height: 16),
        _buildOtherItemsCards(),

        // _buildOtherItemsCard(summary['otherItems'] ?? []),
        // const SizedBox(height: 16),
        // _buildInvoiceCard(summary.invoiceData),
      ],
    );
  }

  Widget _buildCompanyHeader(String companyName) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12),
        // boxShadow: [
        //   BoxShadow(
        //     color: Colors.grey.withOpacity(0.1),
        //     spreadRadius: 1,
        //     blurRadius: 5,
        //     offset: const Offset(0, 2),
        //   ),
        // ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            companyName,
            style: const TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          Image.asset(Assets.iconAppLogo, width: 63, height: 63),
        ],
      ),
    );
  }



  Widget _buildProfitCard(Map<String, dynamic> summary) {
    print(' data.data---- 1111---> summary : ${summary}');
    // var data = context.watch<HomeBtmMoreBloc>().state.data;

    // final data = context.select((HomeBtmMoreBloc bloc) => bloc.state.data);

    // print(' data.data--22222--HomeBtmMoreBloc--->: ${data}');
    return BlocSelector<
      HomeBtmMoreBloc,
      HomeBtmMoreState,
      Map<String, dynamic>?
    >(
      selector: (state) => state.data,
      builder: (BuildContext context, Map<String, dynamic>? state) {
        print(' data.data--33333--HomeBtmMoreBloc--->: ${state}');

        return FinancialCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '本年累计盈利 (元)',
                    style: TextStyle(color: Colors.black54, fontSize: 14),
                  ),
                  // DropdownMenu<String>(
                  //   textAlign : TextAlign.right,
                  //   alignmentOffset:Offset(0,10),
                  //     trailingIcon: const Icon(Icons.arrow_drop_down_circle),
                  //   menuStyle: const MenuStyle(
                  //     backgroundColor: MaterialStatePropertyAll(Colors.black),
                  //   ),
                  //   initialSelection: 'home',
                  //   onSelected: (String? value) {
                  //     // 处理选择
                  //   },
                  //   dropdownMenuEntries: const [
                  //     DropdownMenuEntry(value: 'home', label: '工作地点'),
                  //     DropdownMenuEntry(value: 'work', label: '工作地点'),
                  //     DropdownMenuEntry(value: 'school', label: '学校'),
                  //   ],
                  // ),
                  DropdownButton<int>(
                    value: selectedYear,
                    menuMaxHeight: 200.0,
                    alignment: AlignmentDirectional.topStart,
                    isExpanded: false,
                    items:
                        List.generate(
                              16,
                              (index) => DateTime.now().year - index,
                            )
                            .map(
                              (e) => DropdownMenuItem(
                                value: e,
                                child: Text(
                                  '$e',
                                  style: const TextStyle(fontSize: 14),
                                ),
                              ),
                            )
                            .toList(),
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          selectedYear = value;
                        });
                        // context.read<HomeBloc>().add(ChangeYear(value));
                        context.read<HomeBtmMoreBloc>().add(HomeBtmYearEvent(value),);
                        int quarter = ['第一季度', '第二季度', '第三季度', '第四季度',].indexOf(jidu);
                        context.read<HomeBtmMoreBloc>().add(HomeBtmYearJiDuEvent(quarter),);
                      }
                    },
                    underline: Container(),
                    icon: const Icon(
                      Icons.keyboard_arrow_down,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 6),
              Text(
                state?['累计盈利'] ?? summary['累计盈利'],
                style: const TextStyle(
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF000000),
                ),
              ),
              const SizedBox(height: 19),
              Container(
                height: 1,
                decoration: BoxDecoration(
                  color: Color(0xFFD6D6D6),
                  borderRadius: BorderRadius.circular(12),
                ),
                width: double.infinity,
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '总收入',
                          style: TextStyle(color: Colors.grey, fontSize: 14),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          state?['总收入'] ?? summary['总收入'],
                          style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '总支出',
                          style: TextStyle(color: Colors.grey, fontSize: 14),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          state?['总支出'] ?? summary['总支出'],
                          style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  // 获取当前是第几季度
  int getCurrentQuarter() {
    final now = DateTime.now();
    return (now.month - 1) ~/ 3 + 1;
  }

  // 或者更详细的方法
  String getCurrentQuarterString() {
    final now = DateTime.now();
    final quarter = (now.month - 1) ~/ 3 + 1;
    switch (quarter) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }

  Widget _buildOtherItemsCards() {

    print(
      " ---------------  _buildOtherItemsCards  ------ data : -----------",
    );
    // var data = context.watch<HomeBtmMoreBloc>().state.btmData;

    return BlocListener<AuthBloc, AuthState>(
      listener: (context, state) {
        if (state is AuthAuthenticated) {
          // 刷新数据
          context.read<HomeBtmMoreBloc>().add(HomeBtmYearJiDuEvent(jiduNum),);
        }
      },
      child: BlocSelector<
        HomeBtmMoreBloc,
        HomeBtmMoreState,
        Map<String, dynamic>?
      >(
        selector: (state) => state.btmData,
        builder: (BuildContext context, Map<String, dynamic>? state) {
          print(' data.data--33333--_buildOtherItemsCards--->: ${state}');
          return FinancialCard(
            child: Column(
              mainAxisSize: MainAxisSize.min, // 添加这行
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          margin: const EdgeInsets.only(right: 8),
                          height: 15,
                          width: 3,
                          color: Color(0xFF41C7DD),
                        ),
                        const Text(
                          '其他款项',
                          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                        ),
                      ],
                    ),
                    DropdownButton<String>(
                      value: jidu,
                      items: ['第一季度', '第二季度', '第三季度', '第四季度']
                          .map(
                            (e) => DropdownMenuItem(
                              value: e,
                              child: Text(
                                e,
                                style: const TextStyle(fontSize: 14),
                              ),
                            ),
                          )
                          .toList(),
                      onChanged: (value) {
                        if (value != null) {
                          setState(() {
                            jidu = value;
                          });





                          int quarter = [
                            '第一季度',
                            '第二季度',
                            '第三季度',
                            '第四季度',
                          ].indexOf(value);

                          jiduNum = quarter;
                          // 处理季度选择逻辑
                          context.read<HomeBtmMoreBloc>().add(
                            HomeBtmYearJiDuEvent(jiduNum),
                          );
                        }
                      },
                      underline: Container(),
                      icon: const Icon(
                        Icons.keyboard_arrow_down,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),

                Column(
                  children: [
                    Row(
                      children: [
                        Expanded(child: _buildItemsCards('应收账款', state?['应收账款'] ?? '--')),
                        SizedBox(width: 12),
                        Expanded(child: _buildItemsCards('应付账款', state?['应付账款'] ?? '--')),
                      ],
                    ),
                    SizedBox(height: 12),
                    Column(
                      children: [
                        Row(
                          children: [
                            Expanded(child: _buildItemsCards('销项税额', state?['销项税额'] ?? '--')),
                            SizedBox(width: 12),
                            Expanded(child: _buildItemsCards('进项税额', state?['进项税额'] ?? '--')),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 12),
                    Column(
                      children: [
                        Row(
                          children: [
                            Expanded(flex:1, child: _buildItemsCards('营业收入', state?['营业收入'] ?? '--')),
                            SizedBox(width: 12),
                            Expanded(flex:1, child: _buildItemsCards('实缴税金', state?['实缴税金'] ?? '--')),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),

                // 前两行每行两个项目
                const SizedBox(height: 16),
                Row(
                  children: [
                    Container(
                      margin: const EdgeInsets.only(right: 8),
                      height: 15,
                      width: 3,
                      color: Color(0xFF41C7DD),
                    ),
                    const Text(
                      '发票',
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                Row(
                  children: [
                    Expanded(child: _buildFaPiaoCards('当月销项发票张数', state?['销项数量'] ?? '--')),
                    Container(width: 2,height: 26,color: Color(0xffD6D6D6),),
                    Expanded(child: _buildFaPiaoCards('发票总金额', state?['销项金额'] ?? '--')),
                  ],
                ),
                const SizedBox(height: 16),
                Container(width: double.infinity,height: 1,color: Color(0xffD6D6D6),),
                const SizedBox(height: 16),
                Row(
                  children: [
                    Expanded(child: _buildFaPiaoCards('当月进项发票张数', state?['进项数量'] ?? '--')),
                    Container(width: 2,height: 26,color: Color(0xffD6D6D6),),
                    Expanded(child: _buildFaPiaoCards('发票总金额', state?['进项数量'] ?? '--')),
                  ],
                ),
                const SizedBox(height: 16),

                // 第五个项目单独一行
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildFaPiaoCards(String titleName, String valusInfo) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center, // 添加这行
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(valusInfo, style: TextStyle(color: Colors.black, fontSize: 16)),
          Text(
            titleName,
            style: TextStyle(color: Colors.black, fontSize: 12),
          ),
        ],
      ),
    );
  }


  Widget _buildItemsCards(String titleName, String valusInfo) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: Color(0xFF41C7DD)),
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min, // 添加这行
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 30,
            decoration: BoxDecoration(
              color: Color(0xFF41C7DD),
              borderRadius: BorderRadius.vertical(top: Radius.circular(5)),
            ),
            child: Align(
              alignment: Alignment.center,
              child: Text(titleName, style: TextStyle(color: Colors.white)),
            ),
          ),

          SizedBox(
            height: 46,
            child: Align(
              alignment: Alignment.center,
              child: Text(
                valusInfo,
                style: TextStyle(color: Colors.black, fontSize: 20),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOtherItemsCard(List<OtherItem> items) {
    // 确保有5个项目，与UI匹配
    while (items.length < 5) {
      items.add(OtherItem(title: '', amount: 0.0));
    }
    items = items.take(5).toList();
    items[0].title = '应收账款';
    items[1].title = '应付账款';
    items[2].title = '销项税额';
    items[3].title = '进项税额';
    items[4].title = '实缴税金';

    var state = context.watch<HomeBtmMoreBloc>().state;

    return FinancialCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '| 其他款项',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
              DropdownButton<String>(
                value: '第一季度',
                items: ['第一季度', '第二季度', '第三季度', '第四季度']
                    .map(
                      (e) => DropdownMenuItem(
                        value: e,
                        child: Text(e, style: const TextStyle(fontSize: 14)),
                      ),
                    )
                    .toList(),
                onChanged: (value) {
                  if (value != null) {
                    // 处理季度选择逻辑
                    print('Selected quarter: $value');
                  }
                },
                underline: Container(),
                icon: const Icon(Icons.keyboard_arrow_down, color: Colors.grey),
              ),
            ],
          ),
          const SizedBox(height: 16),
          // 前两行每行两个项目
          GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 12,
              mainAxisSpacing: 12,
              childAspectRatio: 3.0,
            ),
            itemCount: 4,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              final item = items[index];
              return Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
                decoration: BoxDecoration(
                  color: const Color(0xFF41C7DD).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: const Color(0xFF41C7DD).withOpacity(0.5),
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.title,
                      style: const TextStyle(
                        color: Colors.black54,
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 6),
                    Text(
                      item.amount.toStringAsFixed(2),
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                        color: Color(0xFF41C7DD),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
          const SizedBox(height: 12),
          // 第五个项目单独一行
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: const Color(0xFF41C7DD).withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: const Color(0xFF41C7DD).withOpacity(0.5),
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  items[4].title,
                  style: const TextStyle(color: Colors.black54, fontSize: 14),
                ),
                const SizedBox(height: 6),
                Text(
                  items[4].amount.toStringAsFixed(2),
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 18,
                    color: Color(0xFF41C7DD),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }




}
